package com.hudsonmq.spring.handler.netty;


import com.google.gson.reflect.TypeToken;
import com.hudson.codec.domain.RemotingCommand;
import com.hudson.common.enums.MessageTypeEnum;
import com.hudson.core.json.JSONUtil;
import com.hudsonmq.spring.HudsonMQClientController;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author: 渔小鲤
 * @DateTime: 2025/7/24 11:34
 **/
public class BrokerInfoHandler extends SimpleChannelInboundHandler<RemotingCommand> {

    private static final Logger logger = LoggerFactory.getLogger(BrokerInfoHandler.class);


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.debug("连接成功");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RemotingCommand message) throws Exception {
        if (support(message.getType())) {
            Map<String, String> brokerInfo = JSONUtil.fromJson(new String(message.getBody(), StandardCharsets.UTF_8), new TypeToken<Map<String, String>>() {
            });
            HudsonMQClientController.BROKER_ADDRESS_MAP.putAll(brokerInfo);
            if(HudsonMQClientController.START_COUNT_DOWN_LATCH.getCount() > 0){
                HudsonMQClientController.START_COUNT_DOWN_LATCH.countDown();
            }
        }
        ctx.fireChannelRead(message);
    }

    public boolean support(String type) {
        return MessageTypeEnum.GET_BROKER_INFO.getType().equals(type);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.debug("consumer 获取 broker 信息失败");
        logger.debug(cause.getMessage());
    }

}